//
//  Connection.m
//  NewYear
//
//  Created by dllo on 15/3/2.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "Connection.h"

@implementation Connection
- (void)dealloc
{
    Block_release(_secBlock);
    [_recive release];
    [super dealloc];
}
- (instancetype)init
{
    self =[super init];
    if(self){
        self.recive =[NSMutableData data];
    }
    return self;
}


// 网址分为两部分,一部分是固定的内容,一部分是参数

// 从外面传过来网址,然后在单独的类的里面将进行的网络请求,得到数据以后,将内容返回给需要的界面
+ (void)connectionWithUrl:(NSString *)urlStr parmaters:(NSMutableDictionary *)parmaters  block:(void(^)(NSData *data))block
{
    Connection *conn =[[Connection alloc]init];
    conn.secBlock =block;
    [conn startConnection:urlStr parmaters:parmaters];
    [conn release];
    
}
- (void)startConnection:(NSString *)urlStr parmaters:(NSDictionary *)parmaters
{
    // 第一步:准备网址
    NSString *str =@"";
    for (NSString *key in [parmaters allKeys]) {
        if([str length] == 0){
            str =[NSString stringWithFormat:@"?%@=%@",key,[parmaters objectForKey:key]];
        }else{
            str = [NSString stringWithFormat:@"%@&%@=%@",str,key,[parmaters objectForKey:key]];
        }
    }
    
    NSString *urlser =[NSString stringWithFormat:@"%@%@",urlStr,str];
    urlser = [urlser stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    

    NSURL *url =[NSURL URLWithString:urlser];
    
    // 第二步:将网址和将要上传的内容封装起来
    NSMutableURLRequest *urlre =[NSMutableURLRequest requestWithURL:url];
    
    // 服务器告诉客户端,请求方式是get患上post,无非就是参数是否拼接到网址
    [urlre setHTTPMethod:@"GET"];
    
    // 第三步:将封装的内容放到网络连接里,通过网络连接来解析将要找到的网址服务器,并将内容传给服务器,最终获得数据
    
    // 网络连接分为同步连接和异步连接
    // 异步网络连接
    [NSURLConnection connectionWithRequest:urlre delegate:self];
}


// 异步网络请求是需要通果盘协议来获得网络请求的数据
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//    NSHTTPURLResponse *myRes =(NSHTTPURLResponse *)response;
//    NSDictionary *dic =[myRes allHeaderFields];
}


// 获得请求数据,根据请求的数据的大小不同,这个协议方法可以走很多次,每次传过来一部分数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_recive appendData:data];
}


// 数据全部传过来以后,会走下面的协议,结束网络请求
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//    NSString *str =[[NSString alloc]initWithData:_recive encoding:NSUTF8StringEncoding];
//    NSLog(@">>>>>%@",str);// 打印网络请求的到的数据
//    if([self.delegate respondsToSelector:@selector(sendData: flag:)]){
//        [self.delegate sendData:_recive flag:self.flag];
//    }
    self.secBlock(_recive);
    
    // Block
//    self.connectBlock(_recive);
}



// 请求失败时,会走错误协议,并获得错误信息
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error = %@",error);
    
}

@end
